package com.lez.flowpractice2.viewmodel

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lez.flowpractice2.model.Article
import com.lez.flowpractice2.net.RetrofitClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

class ArticleViewModel(app:Application): AndroidViewModel(app) {

    val articles = MutableLiveData<List<Article>>()

    fun searchArticles(key: String) {
        viewModelScope.launch {
            flow {
                val list = RetrofitClient.articleApi.searchArticles(key)
                emit(list)
            }.flowOn(Dispatchers.IO)
                .catch { e-> e.printStackTrace() }
                .collect {
                    Log.i("info","返回值：${it}")
                    articles.setValue(it)
                }
        }
    }

}
